package com.p2p.front.web.controller;

import java.awt.image.BufferedImage;
import java.util.Date;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.p2p.base.annotation.LoginNeedless;
import com.p2p.base.cache.Cache;
import com.p2p.base.model.ValidateCodeSend;
import com.p2p.base.model.ValidateCodeSend.BizTypeEnum;
import com.p2p.base.model.ValidateCodeSend.SendTypeEnum;
import com.p2p.base.service.ValidateCodeSendService;
import com.p2p.base.util.AES;
import com.p2p.base.util.Const;
import com.p2p.base.web.controller.BaseController;
import com.p2p.front.dal.model.User;
import com.p2p.front.service.UserService;

@Controller
@LoginNeedless
public class CaptchaController extends BaseController {

	@Resource
	private Producer captchaProducer = null;

	@Resource
	private Cache defaultCache;
	@Resource
	private UserService userService;

	@Resource
	private ValidateCodeSendService validateCodeSendService;
	private Logger logger = Logger.getLogger(this.getClass());

	@RequestMapping("/sendKaptchaByEmail")
	public void sendKaptchaByEmail(@RequestParam String email,
			HttpServletResponse response) {
		boolean succeed = true;
		try {
			if (StringUtils.isBlank(email)) {
				succeed = false;
			} else {
				User user = userService.findByEmail(email);
				if (user != null) {
					ValidateCodeSend validateCodeSend = new ValidateCodeSend();
					validateCodeSend.setSendIdentity(email);
					validateCodeSend.setSendType(SendTypeEnum.EMAIL);
					validateCodeSend.setBizType(BizTypeEnum.Common);
					validateCodeSend.setEffectMinute(2);
					validateCodeSendService.createAndSendCheckCode(
							validateCodeSend).getResultCode();
				} else {
					succeed = false;
				}
			}
		} catch (Exception e) {
			logger.error("验证码生成失败");
			e.printStackTrace();
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("succeed", succeed);
		if(!succeed){
			jsonObject.put("msg", "邮箱为空，或者不存在");
		}
		super.returnJsonObject(response, jsonObject);

	}

	@RequestMapping("/getKaptchaImage")
	public void getKaptchaImage(HttpServletRequest request,
			HttpServletResponse response) {
		String sSrc = new Date().getTime() + "";
		String key;
		try {
			key = AES.Encrypt(sSrc, Const.CAPTCHA_KEY);
			String code = (String) defaultCache.getValue(key);
			System.out.println("******************上次的验证码是: " + code
					+ "******************");

			response.setDateHeader("Expires", 0);
			// Set standard HTTP/1.1 no-cache headers.
			response.setHeader("Cache-Control",
					"no-store, no-cache, must-revalidate");
			// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
			response.addHeader("Cache-Control", "post-check=0, pre-check=0");
			// Set standard HTTP/1.0 no-cache header.
			response.setHeader("Pragma", "no-cache");
			// return a jpeg
			response.setContentType("image/jpeg");
			// create the text for the image
			String capText = captchaProducer.createText();
			System.out.println("******************本次的验证码是: " + capText
					+ "******************");
			// store the text in the session
			defaultCache.add(key, capText, 3 * 60);
			// create the image with the text
			BufferedImage bi = captchaProducer.createImage(capText);
			ServletOutputStream out = response.getOutputStream();

			// write the data out
			ImageIO.write(bi, "jpg", out);
			try {
				out.flush();
			} finally {
				out.close();
			}
		} catch (Exception e) {
			logger.error("验证码生成失败");
			e.printStackTrace();
		}

	}
}
